package com.tianyadu.security.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @FileName: TimeInterceptor
 * @Description:
 * @author: xueyj
 * @create: 2018-12-05 07:11
 */
@Component
@Slf4j
public class TimeInterceptor implements HandlerInterceptor {

    /**
      * @Description: 前置过滤器，在业务处理器处理请求之前被调用
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/5 7:13
      */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("preHandle过滤器被执行了");
        log.info("被过滤类名，【{}】，被过滤方法，【{}】",
                ((HandlerMethod)handler).getBean().getClass().getName(),
                ((HandlerMethod)handler).getMethod().getName());
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    /**
      * @Description: 后置过滤器,在业务处理器处理请求完成之后，生成视图之前执行，异常情况，不会触发该过滤器
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/5 7:14
      */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        log.info("postHandle过滤器被执行了");
        Long start = (Long) request.getAttribute("startTime");
        log.info("time interceptor 耗时:【{}】", (System.currentTimeMillis() - start));
    }

    /**
      * @Description: 在DispatcherServlet完全处理完请求之后被调用，可用于清理资源，不论正常返回或异常返回，都会执行该过滤器
      * 若正常返回，异常信息为空，否则异常信息不为空
      * @return:
      * @author:
      * @date:   2018/12/5 7:15
      */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("afterCompletion过滤器被执行了");
        Long start = (Long) request.getAttribute("startTime");
        log.info("time interceptor 耗时:【{}】", (System.currentTimeMillis() - start));
        log.info("异常信息，【{}】", ex);
    }
}
